package me.olook.netease.song.rank.task;

import me.olook.netease.song.rank.annotation.TimerJobTypeName;
import me.olook.netease.song.rank.biz.TimerJobService;
import me.olook.netease.song.rank.biz.WeiboUserService;
import me.olook.netease.song.rank.entity.TimerJob;
import me.olook.netease.song.rank.entity.WeiboUser;
import me.olook.netease.song.rank.util.WeiBoUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author zhaohw
 * @date 2018-05-24 16:04
 */
@TimerJobTypeName(value = "关键词搜索")
public class WeiboUserTask implements Job {

    private static Logger log = LoggerFactory.getLogger(WeiboUserTask.class);

    @Autowired
    private WeiboUserService weiboUserService;

    @Autowired
    private TimerJobService timerJobService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        JobKey jobKey = context.getTrigger().getJobKey();

        Optional<TimerJob> timerJob = timerJobService.findByNameAndGroup(jobKey.getName(),jobKey.getGroup());
        if(!timerJob.isPresent()){
            return;
        }
        long start = System.currentTimeMillis();
        List<WeiboUser> users = new ArrayList<>();

        AtomicBoolean flag = new AtomicBoolean(true);
        int page = 1;

        while(flag.get()){
            String result = WeiBoUtil.mobileSearch(timerJob.get().getJobParam(),page++);
            flag.set(WeiBoUtil.searchDataClear(timerJob.get().getJobParam(),result,users));
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        users.forEach(p->{
            weiboUserService.save(p);
        });
        log.info("任务：{} 获取数据：{} 条 , 耗时：{} ",timerJob.get().getJobName() ,users.size(),System.currentTimeMillis()-start);
    }
}
